<?php

/**
 * Description of TemplatesController
 *
 * @author Poh Nean
 */
class TemplatesController extends PsController
{
    public $layout = 'manage';
	
	public function accessRules()
	{
		return CMap::mergeArray(array(
					array('allow',
						'roles' => array('ManageAgency.Template.Manage'),
					),
						), parent::accessRules());
	}
	
	public function actionIndex()
	{
		$template = new Template('search');
		$template->unsetAttributes();

		if (isset($_GET['Template'])) {
			$template->attributes = $_GET['Template'];
		}
		$dataProvider = $template->ofCurrentAgency()->search($_GET['pagesize']);


		$data = array();
		$data['dataProvider'] = $dataProvider;
		$data['template'] = $template;

		$this->render('index', $data);
	}

	public function actionCreate($type = '', $backUrl = null)
	{
		$template = new Template();		
		if (isset($_POST['Template'])) {
			$template->attributes = $_POST['Template'];
			$template->owner_party_id = Yii::app()->user->getSelectedAgency()->party_id;			
			$template->settings = json_encode($_POST['Template']['settings']);
			
			if ($template->save()) {
				if (isset($backUrl)) {
					$this->redirect(urldecode($backUrl));
				} else {
					$this->redirect(array('templates/'));
				}
			}
		} else {
			// Set defailts
			$template->name = 'Untitled';
			$template->settings = array(
				'marginTop' => 10,
				'marginLeft' => 10,
				'marginBottom' => 10,
				'marginRight' => 10,
			);
			if (!empty($type)) {
				$template->type = $type;
			}
		}
		
		$data = array();
		$data['template'] = $template;
		
		$this->render('create', $data);
	}
	
	public function actionUpdate($id, $backUrl = null) {
		$template = $this->loadTemplate($id);	
		
		if (isset($_POST['Template'])) {
			$post = Yii::app()->sanitizer->getOriginalPost();
			$template->attributes = $post['Template'];	
			$template->settings = json_encode($post['Template']['settings']);
			
			if ($template->save()) {
				PsSystemMessage::add('Template saved successfully.', 'success');
				
//				if (isset($backUrl)) {
//					$this->redirect(urldecode($backUrl));
//				} else {
					$this->refresh();
//				}
//				$this->redirect(array('templates'));
			}
		}
		
		$data = array();
		$data['template'] = $template;
		
		$this->render('update', $data);
	}
	
	public function actionHeaderFooters() {
		$this->render('headerFooters');
	}

	public function actionDesign($id = null)
	{
		$this->layout = '//layouts/plain';

		$data = array();
		$data['id'] = $id;

		$this->render('design', $data);
	}

	public function actionPreview($id)
	{
		$this->layout = 'common.views.layouts.blank';
		$template = $this->loadTemplate($id);

		$pageSettings = $template->settings;
		$pagesStyle = 'width: ' . $pageSettings['page']['width'] * $pageSettings['dpm'] . 'px; height: ' . $pageSettings['page']['height'] * $pageSettings['dpm'] . 'px;';

		$data = array();
		$data['template'] = $template;
		$data['pagesStyle'] = $pagesStyle;

		$this->render('preview', $data);
	}

	public function actionPrint($id, $raw = false)
	{
		$this->layout = 'common.views.layouts.blank';
		$template = $this->loadTemplate($id);

		$settings = $template->settings;
		$pagesStyle = 'width: ' . $settings['page']['width'] * $settings['dpm'] . 'px; height: ' . $settings['page']['height'] * $settings['dpm'] . 'px;';

		$pageOrientation = 'P';
		if ($settings['page']['width'] > $settings['page']['height']) {
			$pageOrientation = 'L';
		}

		$data = array();
		$data['template'] = $template;
		$data['pagesStyle'] = $pagesStyle;

		$html = $this->renderPartial('print', $data, true);

		if ($raw) {
			echo $html;
			Yii::app()->end();
		}

		Yii::import('common.lib.wkhtmltopdf.WKPDF');

		// Create PDF object.
		$dir = $_SERVER["DOCUMENT_ROOT"] . '/generated/factsheet/';
		$pdf = new WKPDF($dir);
		// Set PDF's HTML
		$pdf->set_html($html);
		$pdf->set_margins(0, 0, 0, 0);

		if (strstr('orion.propsage.com', $_SERVER["SERVER_NAME"])) {
			$pdf->username = 'pohnean';
			$pdf->password = 'passw0rd';
		}

		// Convert HTML to PDF
		$pdf->render();
		// Output PDF. The file name is suggested to the browser.

		$tmpPdf = $dir . mt_rand() . '.pdf';
		$pdf->output(WKPDF::$PDF_SAVEFILE, $tmpPdf);

		// embed print function using tcpdf
		Yii::import('common.lib.tcpdf.tcpdf.TCPDF');
		Yii::import('common.lib.fpdi.FPDI');
		$tcpdf = new TCPDF();
		$pdf = new FPDI();

		// Set defaults
		$pdf->setHeaderMargin(0);
		$pdf->setPrintHeader(false);
		$pdf->setFooterMargin(0);
		$pdf->setPrintFooter(false);
		$pdf->SetMargins(0, 0, 0, true);
		$pdf->setSourceFile($tmpPdf);

		$pageCount = $pdf->current_parser->page_count;

		for ($pageNum = 1; $pageNum <= $pageCount; $pageNum++) {

			// Render page
			$pdf->AddPage();
			$pdf->setPageOrientation('P', false, 0);
			$tplIdx = $pdf->importPage($pageNum);

			$pdf->useTemplate($tplIdx, 0, 0, 210);
		}

		$pdf->Output('factsheet.pdf', 'I');

		@unlink($tmpPdf);
	}

	public function actionDelete($id)
	{
		$response = array();

		$template = $this->loadTemplate($id);

		if ($template == null) {
			$response['result'] = 'failure';
			$response['errorMsg'] = 'Object not found';
		} else {
			if ($template->delete()) {
				$response["result"] = 'success';
				$response["id"] = $template->id;
			} else {
				$response["result"] = 'failure';
				$response["error"] = $template->getErrors();
				$response["errorMsg"] = 'Error deleting brochure.';
			}
		}

		print json_encode($response);
	}

	public function actionAjaxSave($id = null)
	{
		$response = array();

		if (isset($_POST)) {
			if ($id === null) {
				$template = new Template();
				$template->owner_party_id = Yii::app()->user->getSelectedAgency()->party_id;;
			} else {
				$template = $this->loadTemplate($id);
			}

			$postData = Yii::app()->sanitizer->getOriginalPost();
			$postData = json_decode($postData['data'], true);

			$template->name = $postData['name'];
			$template->type = $postData['type'];

			$template->settings = json_encode($postData['settings']);
			$template->widgets = json_encode($postData['widgets']);
			$template->header_html = $postData['header_html'];
			$template->header_style = $postData['header_style'];
			$template->footer_html = $postData['footer_html'];
			$template->footer_style = $postData['footer_style'];
			$template->pages_html = $postData['pages_html'];
			$template->pages_style = $postData['pages_style'];

			if ($template->save()) {
				$response['id'] = $template->id;
				$response['result'] = 'success';
			} else {
				$errors = $template->getErrors();
				$error = current($errors);

				$response['result'] = 'failure';
				$response['errorMsg'] = $error[0];
			}
		}

		print json_encode($response);
	}

	public function actionAjaxLoad($id)
	{
		$template = $this->loadTemplate($id);

		$data = $template->attributes;
		unset($data['owner_party_id']);

		$response = array();
		$response['result'] = 'success';
		$response['data'] = $data;

		print json_encode($response);
	}

	public function loadTemplate($id)
	{
		$template = Template::model()->ofCurrentAgency()->findByPk($id);

		if ($template == null) {
			throw new PsPageNotFoundException();
		}

		return $template;
	}

}

?>
